package top.kaoshanji.p1ch03a;

import org.apache.hc.core5.http.ContentType;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

/**
 * 代码清单-p1ch03a-60页a：读入初始化参数的计数器
 * URL访问地址：/initCounter
 * @author kaoshanji
 * ^_^
 * create time 2025/4/3 11:27
 */
public class InitCounter extends HttpServlet {

    // 实例属性，可以被不同的方法共享，A方法赋值，B方法读取，C方法修改
    int count;

    @Override
    public void init() throws ServletException {
        String initial = getInitParameter("initial");
        try {
            count = Integer.parseInt(initial);
        } catch (NumberFormatException e) {
            count = 0;
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置请求对象的编码
        req.setCharacterEncoding(StandardCharsets.UTF_8.name());

        // 设置响应对象的编码和内容格式
        resp.setContentType(ContentType.TEXT_PLAIN.toString());
        PrintWriter out = resp.getWriter();

        count++;

        out.println("Since loading (and with a possible initialization");
        out.println("parameter figured in), this servlet has been accessed");
        out.println(count + " times.");

    }


}
